package com.base_data_handler.sx.handler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.commons.dbutils.QueryRunner;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base_data_handler.utils.Constant;
import com.base_data_handler.utils.DBUtil;
import com.base_data_handler.utils.DataSourceUtils;
import com.base_data_handler.utils.DruidPlugin;
import com.base_data_handler.utils.HttpRequest;
import com.base_data_handler.utils.HttpUtils;
import com.base_data_handler.utils.StringUtils;

import net.sf.ehcache.search.parser.MCriteria.Simple;
/**
 * cimmiss  陕西省所有自动站区域站天气数据 ，每半小时采集一次,采集时间为整点 6分钟和16分钟
 * @param urlStr
 * @return
 * 陕西
 * BEXA_BAOJI_YW&pwd=baoji123
 * 甘肃
 * userId=BCLZ_QHZX_qhzx&pwd=qhzx
 */
public class SX_Auto_Area_Position_Handler {
//	private	static QueryRunner qr=new QueryRunner(DruidPlugin.getDataSource());
	private	static QueryRunner qr=new QueryRunner(DataSourceUtils.getDatasSource());
	private static final Logger log = Logger.getLogger(SX_Auto_Area_Position_Handler.class.getName());
	
//	Province=陕西省（自动站） 、陕西（区域站资料）
	public static boolean getCimmisSX_Hours(String province) throws SQLException{
//		SimpleDateFormat sm=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String times="",times2="";//20170627000000
		Calendar c=Calendar.getInstance();
		int year=c.get(Calendar.YEAR);
		String month=(c.get(Calendar.MONTH)+1)+"";
		String day=c.get(Calendar.DAY_OF_MONTH)+"";
		String hour=c.get(Calendar.HOUR_OF_DAY)-8+"";
		
		if(month.length()==1)month="0"+month;
		if(day.length()==1)day="0"+day;
		if(hour.length()==1)hour="0"+hour;
		
		System.out.println("year="+year+",month="+month+",day="+day+",hour="+hour);
		times=year+month+day+hour+"0000";
		String url="http://"+Constant.CMISS_HOST_PORT+"/cimiss-web/api";
//		String param="userId="+Constant.CMISS_NAME+"&pwd="+Constant.CMISS_PASS+"&interfaceId=getSurfEleByTime&dataCode=SURF_CHN_MUL_HOR"
//				+ "&elements=Station_Name,Province,City,Cnty,Town,Datetime,REP_CORR_ID,Station_Id_C,Lat,Lon,Admin_Code_CHN,PRS,TEM,DPT,RHU,VAP,PRE_1h,PRE_3h,PRE_6h,PRE_12h,PRE_24h,PRE,WIN_D_S_Max,WIN_S_Max,WIN_S_Max_OTime,VIS"
//				+ "&times="+times+"&dataFormat=json&eleValueRanges=Province:"+province+";&staLevels=011,012,013,014";
//		System.out.println(url+"?"+param);
		//全国
		String param="userId="+Constant.CMISS_NAME+"&pwd="+Constant.CMISS_PASS+"&interfaceId=getSurfEleByTime&dataCode=SURF_CHN_MUL_HOR"
				+ "&elements=Station_Name,Province,City,Cnty,Town,Datetime,REP_CORR_ID,Station_Id_C,Lat,Lon,Admin_Code_CHN,PRS,TEM,DPT,RHU,VAP,PRE_1h,PRE_3h,PRE_6h,PRE_12h,PRE_24h,PRE,WIN_D_S_Max,WIN_S_Max,WIN_S_Max_OTime,VIS"
				+ "&times="+times+"&dataFormat=json&staLevels=011,012,013,014&eleValueRanges=Province:"+province+"";
	
		Map<String, String> map=new HashMap<String, String>();
		String[] key_value = param.split("&");
		for (int i = 0; i < key_value.length; i++) {
			String[] k_v = key_value[i].split("=");
			map.put(k_v[0], k_v[1]);
		 }
//		 System.out.println(url+"&"+param);
		 String str = HttpUtils.sendHttpClientPost(url, map, "utf-8");
		//jdbc
		 savaBatch(str);
//		 System.out.println(str);
		 
//		 QurynerBatch(str);
		 return false;
	}

	private static void QurynerBatch(String str) throws SQLException {
		JSONObject alljson= (JSONObject) JSON.parse(str);
		 if(alljson.getString("returnCode").equals("0")){
			  JSONArray mod = JSON.parseArray(alljson.getString("DS"));
				Object[][] params=new Object[mod.size()][42];
			   JSONObject obj=null;
			   for (int i = 0; i < mod.size(); i++) {
				    obj = (JSONObject) mod.get(i);
//				    System.out.println(mod.get(i));
				    if(StringUtils.isEmpty(obj.getString("Station_Name"))||
					StringUtils.isEmpty(obj.getString("Cnty"))) continue;
				    params[i][0]=obj.getString("Station_Name").trim();
				    params[i][1]=obj.getString("Province").trim();
				    params[i][2]=obj.getString("City").trim();
				    params[i][3]=obj.getString("Cnty").trim();
				    params[i][4]=obj.getString("Town").trim();
				    params[i][5]=obj.getString("Datetime");
				    params[i][6]=obj.getString("Station_Id_C");
				    params[i][7]=obj.getString("Lat");
				    params[i][8]=obj.getString("Lon");
				    params[i][9]=obj.getString("Admin_Code_CHN");
				    
				    String prs="0";
				    if(obj.getString("PRS")!=null&&!obj.getString("PRS").contains("99999")){
				    	prs=obj.getString("PRS");
				    }
				    params[i][10]=prs;
				    
				    String tem="0";
				    if(obj.getString("TEM")!=null&&!obj.getString("TEM").contains("99999")){
				    	tem=obj.getString("TEM");
				    }
				    params[i][11]=tem;
				    
				    String dpt="0";
				    if(obj.getString("DPT")!=null&&!obj.getString("DPT").contains("99999")){
				    	dpt=obj.getString("DPT");
				    }
				    params[i][12]=dpt;
				    
				    String rhu="0";
				    if(obj.getString("RHU")!=null&&!obj.getString("RHU").contains("99999")){
				    	rhu=obj.getString("RHU");
				    }
				    params[i][13]=rhu;
				    
				    
				    String vap="0";
				    if(obj.getString("VAP")!=null&&!obj.getString("VAP").contains("99999")){
				    	vap=obj.getString("VAP");
				    }
				    params[i][14]=vap;
				    String r1h="0",r3h="0",r6h="0",r12h="0",r24h="0";
				    
				    if(obj.getString("PRE_1h")!=null&&!obj.getString("PRE_1h").contains("99999")){
				    	r1h=obj.getString("PRE_1h");
				    }
				    params[i][15]=r1h;
				    
				    if(obj.getString("PRE_3h")!=null&&!obj.getString("PRE_3h").contains("99999")){
				    	r3h=obj.getString("PRE_3h");
				    }
				    params[i][16]=r3h;
				    
				    if(obj.getString("PRE_6h")!=null&&!obj.getString("PRE_6h").contains("99999")){
				    	r6h=obj.getString("PRE_6h");
				    }
				    params[i][17]=r6h;
				    
				    if(obj.getString("PRE_12h")!=null&&!obj.getString("PRE_12h").contains("99999")){
				    	r12h=obj.getString("PRE_12h");
				    }
				    params[i][18]=r12h;
				    
				    if(obj.getString("PRE_24h")!=null&&!obj.getString("PRE_24h").contains("99999")){
				    	r24h=obj.getString("PRE_24h");
				    }
				    params[i][19]=r24h;
				    
				    String pre="0";
				    if(obj.getString("PRE")!=null&&!obj.getString("PRE").contains("99999")){
				    	pre=obj.getString("PRE");
				    }
				    params[i][20]=pre;
				    
				    
				    String win_d_s_max="0";
				    if(obj.getString("WIN_D_S_Max")!=null&&!obj.getString("WIN_D_S_Max").contains("99999")){
				    	win_d_s_max=obj.getString("WIN_D_S_Max");
				    }
				    params[i][21]=win_d_s_max;
				    
				    String win_s_max="0";
				    if(obj.getString("WIN_S_Max")!=null&&!obj.getString("WIN_S_Max").contains("99999")){
				    	win_s_max=obj.getString("WIN_S_Max");
				    }
				    params[i][22]=win_s_max;
				    
				    String win_s_max_otime="0";
				    if(obj.getString("WIN_S_Max_OTime")!=null&&!obj.getString("WIN_S_Max_OTime").contains("99999")){
				    	win_s_max_otime=obj.getString("WIN_S_Max_OTime");
				    }
				    params[i][23]=win_s_max_otime;
				    
				    
				    String vis="0";
				    if(obj.getString("VIS")!=null&&!obj.getString("VIS").contains("99999")){
				    	vis=obj.getString("VIS");
				    }
				    params[i][24]=vis;
				    
				    //设置id
				    params[i][25]=obj.getString("Station_Id_C")+obj.getString("Datetime");
				    
				    //更新
				    params[i][26]=obj.getString("Datetime");
				    params[i][27]=prs;
				    params[i][28]=tem;
				    params[i][29]=dpt;
				    params[i][30]=rhu;
				    params[i][31]=vap;
				    params[i][32]=r1h;
				    params[i][33]=r3h;
				    params[i][34]=r6h;
				    params[i][35]=r12h;
				    params[i][36]=r24h;
				    params[i][37]=pre;
				    params[i][38]=win_d_s_max;
				    params[i][39]=win_s_max;
				    params[i][40]=win_s_max_otime;
				    params[i][41]=vis;
				   
			    }
			   
			    proData2Db(params);
		 }
	}
	
	private static void proData2Db(Object[][] params) throws SQLException{
		StringBuilder sql=new StringBuilder();
		
		sql.append("INSERT INTO   cmiss_all_position_hours ")
		   .append("(Station_Name,Province,City,Cnty,Town,Datetime,Station_Id_C,Lat,Lon,Admin_Code_CHN,PRS,TEM,DPT,RHU,VAP,PRE_1h,PRE_3h,PRE_6h,PRE_12h,PRE_24h,PRE,WIN_D_S_Max,WIN_S_Max,WIN_S_Max_OTime,VIS,id) ")
		   .append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")//26			
		   .append(" ON DUPLICATE KEY UPDATE  ")
		   .append(" Datetime=?,PRS=?,TEM=?,DPT=?,")
		   .append(" RHU =?,VAP=?,PRE_1h=?,PRE_3h=?,")
		   .append(" PRE_6h =?,PRE_12h=?,PRE_24h=?,PRE=?,")
		   .append(" WIN_D_S_Max =?,WIN_S_Max=?,WIN_S_Max_OTime=?,VIS=?");//批量
		
		qr.batch(sql.toString(), params);
	}
	public static void main(String[] args) throws SQLException {
		//早上8点预报，显示从当前时间开始
		getCimmisSX_Hours("甘肃");
		getCimmisSX_Hours("甘肃省");
		System.out.println("执行？");
	}
	
	
	 public static void savaBatch(String str){
    	  PreparedStatement ps = null;
    		 DBUtil db = null;
    		 Connection co = null;
    			StringBuilder sql=new StringBuilder();
    			
    			sql.append("INSERT INTO   cmiss_all_position_hours ")
    			   .append("(Station_Name,Province,City,Cnty,Town,Datetime,Station_Id_C,Lat,Lon,Admin_Code_CHN,PRS,TEM,DPT,RHU,VAP,PRE_1h,PRE_3h,PRE_6h,PRE_12h,PRE_24h,PRE,WIN_D_S_Max,WIN_S_Max,WIN_S_Max_OTime,VIS,id) ")
    			   .append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")//26			
    			   .append(" ON DUPLICATE KEY UPDATE  ")
    			   .append(" Datetime=?,PRS=?,TEM=?,DPT=?,")
    			   .append(" RHU =?,VAP=?,PRE_1h=?,PRE_3h=?,")
    			   .append(" PRE_6h =?,PRE_12h=?,PRE_24h=?,PRE=?,")
    			   .append(" WIN_D_S_Max =?,WIN_S_Max=?,WIN_S_Max_OTime=?,VIS=?");//批量
    		 db = new DBUtil();
    		 try { 
    			co=db.getConnection();
				co.setAutoCommit(false);
				ps = co.prepareStatement(sql.toString());
				 JSONObject alljson= (JSONObject) JSON.parse(str);
				if(alljson.getString("returnCode").equals("0")){
					  JSONArray mod = JSON.parseArray(alljson.getString("DS"));
					   JSONObject obj=null;
					  System.out.println("共有："+mod.size());
					  int j=0;
					   for (int i = 0; i < mod.size(); i++) {
						    obj = (JSONObject) mod.get(i);
						    if(StringUtils.isEmpty(obj.getString("Station_Name"))||
						       StringUtils.isEmpty(obj.getString("Cnty"))) continue;
//						    System.out.println(mod.get(i));
						    ps.setString(1,obj.getString("Station_Name").trim());
						     ps.setString(2,obj.getString("Province").trim());
						     ps.setString(3,obj.getString("City").trim());
						     ps.setString(4,obj.getString("Cnty").trim());
						     ps.setString(5,obj.getString("Town").trim());
						     ps.setString(6,obj.getString("Datetime"));
						     ps.setString(7,obj.getString("Station_Id_C"));
						     ps.setString(8,obj.getString("Lat"));
						     ps.setString(9,obj.getString("Lon"));
						     ps.setString(10,obj.getString("Admin_Code_CHN"));
						    
						    String prs="0";
						    if(obj.getString("PRS")!=null&&!obj.getString("PRS").contains("99999")){
						    	prs=obj.getString("PRS");
						    }
						     ps.setString(11,prs);
						    
						    String tem="0";
						    if(obj.getString("TEM")!=null&&!obj.getString("TEM").contains("99999")){
						    	tem=obj.getString("TEM");
						    }
						     ps.setString(12,tem);
						    
						    String dpt="0";
						    if(obj.getString("DPT")!=null&&!obj.getString("DPT").contains("99999")){
						    	dpt=obj.getString("DPT");
						    }
						     ps.setString(13,dpt);
						    
						    String rhu="0";
						    if(obj.getString("RHU")!=null&&!obj.getString("RHU").contains("99999")){
						    	rhu=obj.getString("RHU");
						    }
						     ps.setString(14,rhu);
						    
						    
						    String vap="0";
						    if(obj.getString("VAP")!=null&&!obj.getString("VAP").contains("99999")){
						    	vap=obj.getString("VAP");
						    }
						     ps.setString(15,vap);
						    String r1h="0",r3h="0",r6h="0",r12h="0",r24h="0";
						    
						    if(obj.getString("PRE_1h")!=null&&!obj.getString("PRE_1h").contains("99999")){
						    	r1h=obj.getString("PRE_1h");
						    }
						     ps.setString(16,r1h);
						    
						    if(obj.getString("PRE_3h")!=null&&!obj.getString("PRE_3h").contains("99999")){
						    	r3h=obj.getString("PRE_3h");
						    }
						     ps.setString(17,r3h);
						    
						    if(obj.getString("PRE_6h")!=null&&!obj.getString("PRE_6h").contains("99999")){
						    	r6h=obj.getString("PRE_6h");
						    }
						     ps.setString(18,r6h);
						    
						    if(obj.getString("PRE_12h")!=null&&!obj.getString("PRE_12h").contains("99999")){
						    	r12h=obj.getString("PRE_12h");
						    }
						     ps.setString(19,r12h);
						    
						    if(obj.getString("PRE_24h")!=null&&!obj.getString("PRE_24h").contains("99999")){
						    	r24h=obj.getString("PRE_24h");
						    }
						     ps.setString(20,r24h);
						    
						    String pre="0";
						    if(obj.getString("PRE")!=null&&!obj.getString("PRE").contains("99999")){
						    	pre=obj.getString("PRE");
						    }
						     ps.setString(21,pre);
						    
						    
						    String win_d_s_max="0";
						    if(obj.getString("WIN_D_S_Max")!=null&&!obj.getString("WIN_D_S_Max").contains("99999")){
						    	win_d_s_max=obj.getString("WIN_D_S_Max");
						    }
						     ps.setString(22,win_d_s_max);
						    
						    String win_s_max="0";
						    if(obj.getString("WIN_S_Max")!=null&&!obj.getString("WIN_S_Max").contains("99999")){
						    	win_s_max=obj.getString("WIN_S_Max");
						    }
						     ps.setString(23,win_s_max);
						    
						    String win_s_max_otime="0";
						    if(obj.getString("WIN_S_Max_OTime")!=null&&!obj.getString("WIN_S_Max_OTime").contains("99999")){
						    	win_s_max_otime=obj.getString("WIN_S_Max_OTime");
						    }
						     ps.setString(24,win_s_max_otime);
						    
						    
						    String vis="0";
						    if(obj.getString("VIS")!=null&&!obj.getString("VIS").contains("99999")){
						    	vis=obj.getString("VIS");
						    }
						     ps.setString(25,vis);
						    
						    //设置id
						     ps.setString(26,obj.getString("Station_Id_C")+obj.getString("Datetime"));
						    
						    //更新
						     ps.setString(27,obj.getString("Datetime"));
						     ps.setString(28,prs);
						     ps.setString(29,tem);
						     ps.setString(30,dpt);
						     ps.setString(31,rhu);
						     ps.setString(32,vap);
						     ps.setString(33,r1h);
						     ps.setString(34,r3h);
						     ps.setString(35,r6h);
						     ps.setString(36,r12h);
						     ps.setString(37,r24h);
						     ps.setString(38,pre);
						     ps.setString(39,win_d_s_max);
						     ps.setString(40,win_s_max);
						     ps.setString(41,win_s_max_otime);
						     ps.setString(42,vis);
						   ps.addBatch();
						   j=i;
						   if(i%1000==0){
							    ps.executeBatch();
								co.commit();
							    ps.clearParameters();
				                ps.clearBatch();
				            	
							 }
					    }
						
				System.out.println("执行了："+j);
				ps.executeBatch();
				co.commit();
				ps.clearParameters();
                ps.clearBatch();
              System.out.println("提交了事务");
             
              }
    		 }catch (SQLException e) {
    			 	e.printStackTrace();
    		  }finally{
					try {
						if (co!=null)
						co.close();
						if (ps!=null)
	   						ps.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	         }
   }
}
